package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinghai.common.constant.CacheConstants;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.utils.DataUtil;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.bean.BeanUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.entity.ApplyStoreDTO;
import com.xinghai.system.domain.entity.StoreGoodDTO;
import com.xinghai.system.domain.entity.StoreUpdateInfoDTO;
import com.xinghai.system.domain.entity.UpdateInfoDTO;
import com.xinghai.system.domain.vo.QdStoreVo;
import com.xinghai.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.rmi.ServerException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 钱包api接口
 *
 * @author xinghai
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/api/store")
public class QdStoreApiController extends BaseController
{
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdStoreService storeService;
    @Autowired
    private IQdStoreGoodService goodService;
    @Autowired
    private IQdOrderService orderService;
    @Autowired
    private IQdUserWalletService userWalletService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysNoticeService noticeService;
    @Autowired
    private ISysConfigService configService;


    /**
     * 查询订单模块列表
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        return success(storeService.getById(user.getAscriptionStore()));
    }


    /**
     * 查询首页通知
     */
    @GetMapping("/getNotice")
    public AjaxResult getNotice()
    {
//        String loginId = StpUtil.getLoginId("");
//        QdUser user = userService.getByLoginId(loginId);
//        QdStore store =storeService.getById(user.getAscriptionStore());
//        if (store!=null&&StringUtils.isNotBlank(store.getStoreNotice())){
//            return success((Object) store.getStoreNotice());
//        }
//        PageUtils.startPage(1,1);
//        PageUtils.orderBy("create_time desc");
//        SysNotice notice = new SysNotice();
//        notice.setNoticeType("2");
//        notice.setStatus("0");
//        List<SysNotice> list = noticeService.selectNoticeList(notice);
//        if (!list.isEmpty()){
//            return success((Object)list.get(0).getNoticeContent());
//        }
        String s = configService.selectConfigByKey("store.notice");
        if (StringUtils.isNotBlank(s)){
            return success((Object) s);
        }
        return success((Object) "欢迎使用本系统！！！");
    }


    /**
     * 查询店铺首页数据
     */
    @GetMapping("/getDataInfo")
    public AjaxResult getDataInfo()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdOrder order = new QdOrder();
        order.setStoreId(user.getAscriptionStore());
        order.setStatus("0");
        order.setDealTime(new Date());
        //order.setParams(DataUtil.getCreateTimeParams());
        List<QdOrder> list = orderService.list(order);
        List<QdOrder> dchList = list.stream().filter(o -> "0".equals(o.getSellerStatus())).collect(Collectors.toList());
        List<QdOrder> yyyList = list.stream().filter(o -> !"0".equals(o.getSellerStatus())&&("1".equals(o.getBuyerType())||"2".equals(o.getBuyerType())||"3".equals(o.getBuyerType())||"4".equals(o.getBuyerType()))).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("dchNum",dchList.size());//待出售订单
        map.put("dchAmount",dchList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//待出售总价
        map.put("yyyNum",yyyList.size());//已预约订单
        map.put("yyyAmount",yyyList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//已预约总价
        return success(map);
    }

    /**
     * 查询分店店铺列表
     */
    @GetMapping("/getChildStoreList")
    public AjaxResult getChildStoreList()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStore child = new QdStore();
        child.setParentStoreId(user.getAscriptionStore());
        List<QdStore> list = storeService.list(child);
        return success(list);
    }


    /**
     * 申请开店
     */
    @PostMapping("/applyStore")
    public AjaxResult applyStore(@Validated @RequestBody ApplyStoreDTO applyStoreDTO)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStore child = new QdStore();
        child.setStoreName(applyStoreDTO.getStoreName());
        if (user.getAscriptionStore()!=null){
            child.setParentStoreId(user.getAscriptionStore());
        }
        QdUser user1 = userService.getByUserPhone(applyStoreDTO.getUserPhone());
        if (user1==null){
            return error("该账号不存在");
        }
        if ("2".equals(user.getUserType())&&user1.getAscriptionStore()!=null&&user1.getStoreLeaderId().equals(user1.getId())){
            return error("该账号已成为店长");
        }
        child.setStoreLeaderId(user1.getId());
        child.setStoreName(applyStoreDTO.getStoreName());
        return success(storeService.applyStore(child));
    }

    /**
     * 查询分店店铺列表
     */
    @GetMapping("/getChildData")
    public AjaxResult getChildData(String storeId)
    {
        QdStore store = storeService.getById(storeId);
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + store.getId());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(store.getId());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + store.getId(), cacheMap);
        }
        QdOrder order = new QdOrder();
        order.setStoreId(store.getId());
        List<QdOrder> listAll = orderService.list(order);
        order.setStatus("0");
//        order.setParams(DataUtil.getCreateTimeParams());
        order.setDealTime(new Date());
        List<QdOrder> list = orderService.list(order);
        List<QdOrder> orderList = listAll.stream().filter(o -> ("0".equals(o.getStatus()) || "1".equals(o.getStatus()))&& "0".equals(o.getSellerStatus())).collect(Collectors.toList());
        //封单
        List<QdOrder> fdList = listAll.stream().filter(o -> "1".equals(o.getStatus())).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("allzsNum",orderList.size());//总在售订单
        map.put("allzsAmonut",orderList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//总在售总价
        map.put("allfdNum",fdList.size());//已预约订单
        map.put("allfdAmonut",fdList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO,BigDecimal::add));//已预约总价

        QdStoreVo finalCacheMap = cacheMap;
//        List<QdOrder> yyList = list.stream().filter(o -> {
//            assert finalCacheMap != null;
//            return (o.getPrice().compareTo(finalCacheMap.getGroupOneMinPrice())>-1&&o.getPrice().compareTo(finalCacheMap.getGroupOneMaxPrice())<0)||
//                    (o.getPrice().compareTo(finalCacheMap.getGroupTwoMinPrice())>-1&&o.getPrice().compareTo(finalCacheMap.getGroupTwoMaxPrice())<0)||
//                    (o.getPrice().compareTo(finalCacheMap.getGroupThreeMinPrice())>-1&&o.getPrice().compareTo(finalCacheMap.getGroupThreeMaxPrice())<0);
//        }).collect(Collectors.toList());
//        List<QdOrder> qgList = list.stream().filter(o -> {
//            return !((o.getPrice().compareTo(finalCacheMap.getGroupOneMinPrice())>-1&&o.getPrice().compareTo(finalCacheMap.getGroupOneMaxPrice())<0)||
//                    (o.getPrice().compareTo(finalCacheMap.getGroupTwoMinPrice())>-1&&o.getPrice().compareTo(finalCacheMap.getGroupTwoMaxPrice())<0)||
//                    (o.getPrice().compareTo(finalCacheMap.getGroupThreeMinPrice())>-1&&o.getPrice().compareTo(finalCacheMap.getGroupThreeMaxPrice())<0));
//        }).collect(Collectors.toList());
        List<QdOrder> yyList = list.stream().filter(o -> "1".equals(o.getBuyerType())||"3".equals(o.getBuyerType())).collect(Collectors.toList());
        List<QdOrder> qgList = list.stream().filter(o -> "2".equals(o.getBuyerType())||"4".equals(o.getBuyerType())).collect(Collectors.toList());
        List<QdOrder> kyyList = list.stream().filter(o -> "0".equals(o.getBuyerType())).collect(Collectors.toList());
        List<QdOrder> dshList = list.stream().filter(o -> "3".equals(o.getBuyerStatus())).collect(Collectors.toList());
        List<QdOrder> yshList = list.stream().filter(o -> "4".equals(o.getBuyerStatus())).collect(Collectors.toList());
        List<QdOrder> wcList = list.stream().filter(o -> "2".equals(o.getSellerStatus())).collect(Collectors.toList());
        if (!yyList.isEmpty()){
            map.put("todayyyNum",yyList.size());//已预约订单
            map.put("todayyyAmonut",yyList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//已预约总价
        }
        if (!qgList.isEmpty()){
            map.put("todayqgNum",qgList.size());//抢购订单
            map.put("todayqgAmonut",qgList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//抢购总价
        }
        if (!kyyList.isEmpty()){
            map.put("todaykyNum",kyyList.size());//剩余可预约订单
            map.put("todaykyAmonut",kyyList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//剩余可预约总价
        }
        if (!dshList.isEmpty()){
            map.put("todaydsNum",dshList.size());//待审核订单
            map.put("todaydsAmonut",dshList.stream().map(QdOrder::getListingFee).reduce(BigDecimal.ZERO, BigDecimal::add));//待审核上架费
        }
        if (!yshList.isEmpty()){
            map.put("todayysNum",yshList.size());//已审核订单
            map.put("todayysAmonut",yshList.stream().map(QdOrder::getListingFee).reduce(BigDecimal.ZERO, BigDecimal::add));//已审核上架费
        }
        if (!wcList.isEmpty()){
            map.put("todaywcNum",wcList.size());//完成订单
            map.put("todaywcAmonut",wcList.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));//完成总价
        }
        return success(map);
    }


    /**
     * 修改店铺信息
     */
    @PostMapping("/updateStoreInfo")
    public AjaxResult updateStoreInfo(@Validated @RequestBody StoreUpdateInfoDTO dto)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStore store = storeService.getById(user.getAscriptionStore());
        String storeName = null;
        BigDecimal gift = null;
        if (!dto.getStoreName().equals(store.getStoreName())){
            storeName = dto.getStoreName();
        }
        if (dto.getAppreciation().compareTo(store.getAppreciation())!=0){
            gift = dto.getAppreciation();
        }
        if (storeName!=null||gift!=null){
            QdUser u = new QdUser();
            u.setAscriptionStore(store.getId());
            List<QdUser> list = userService.list(u);
            String finalStoreName = storeName;
            BigDecimal finalGift = gift;
            list.forEach(m -> {
                if (finalStoreName !=null){
                    m.setStoreName(finalStoreName);
                }
                if (finalGift !=null){
                    m.setGiftValue(dto.getAppreciation());
                }
            });
            userService.updateBatchById(list);
        }
        BeanUtils.copyBeanProp(store,dto);
        storeService.updateById(store);
        return success();
    }

    /**
     * 修改商品信息
     */
    @PostMapping("/updateGood")
    public AjaxResult updateGood(@Validated @RequestBody StoreGoodDTO dto)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStore store = storeService.getById(user.getAscriptionStore());
        QueryWrapper<QdStoreGood> qdStoreGoodQueryWrapper = new QueryWrapper<>();
        qdStoreGoodQueryWrapper.eq("store_id",store.getId());
        QdStoreGood good = goodService.getOne(qdStoreGoodQueryWrapper);
        if (good==null){
            good = new QdStoreGood();
        }
        BeanUtils.copyBeanProp(good,dto);
        if (good.getId()!=null){
            goodService.updateById(good);
        }else {
            good.setStoreId(store.getId());
            good.setStoreName(store.getStoreName());
            good.setStoreImg(store.getStoreImg());
            good.setStoreLeader(store.getStoreLeader());
            good.setStoreLeaderImg(store.getStoreLeaderImg());
            good.setStoreLeaderPhone(store.getStoreLeaderPhone());
            goodService.save(good);
            store.setGroupOneGoodId(good.getId());
            store.setGroupTwoGoodId(good.getId());
            store.setGroupThreeGoodId(good.getId());
        }
        store.setGroupOneImage(good.getGoodImg());
        store.setGroupOneName(good.getGoodName());
        store.setGroupTwoImage(good.getGoodImg());
        store.setGroupTwoName(good.getGoodName());
        store.setGroupThreeImage(good.getGoodImg());
        store.setGroupThreeName(good.getGoodName());
        storeService.updateById(store);
        return success();
    }

    /**
     * 查询商品列表
     */
    @GetMapping("/getGoodList")
    public AjaxResult getGoodList()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStoreGood good = new QdStoreGood();
        good.setStoreId(user.getAscriptionStore());
        List<QdStoreGood> list = goodService.list(good);
        return success(list);
    }

}
